package amalgame.ventas;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import amalgame.data.DatabaseManager;
import amalgame.entity.Actividad;
import amalgame.entity.Util;
import amalgame.entity.db.Categorie;
import amalgame.entity.db.Product;
import amalgame.entity.db.Stock;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

@SuppressLint("SimpleDateFormat")
public class AddProductActivity extends Actividad {
	private Button btn_cancel;
	private Button btn_save;
	private Dialog dialog_confirmation;
	private Util utilman;
	private DatabaseManager manager;
	private Context mContext;

	private EditText txt_name;
	private EditText txt_quantity;
	private Spinner sp_categorie;
	private EditText txt_description;
	private Button btn_photo;
	private ImageButton imb_delete;

	private String pathphoto = "";
	private boolean isEditMode = false;
	private Product product;
	private Stock stock;
	private int idcategorie;
	private Dialog customDialog;

	private final int CAMERA_PIC_REQUEST = 1;

	public static Context fotoContext = null;
	private String picturFile = "";
	public static String PATH_APPDIRs = "sistema_ventas";
	// public static String PATH_APPDIR_multimedia = "/.productsPhotos/"
	// + "registros/Multimedia/";
	public static boolean fotoInsertada = false;
	private static Bitmap thumbnail;
	private final int  ACTIVO = 1;
	private Bitmap bitmap;
	private ImageView imageView ;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.add_product);

		Bundle getuserID = getIntent().getExtras();
		if (getuserID != null) {
			if (getIntent().getExtras().getString("MODE") != null) {
				String mode = getIntent().getExtras().getString("MODE");

				if (mode.equals("EDIT")) {
					isEditMode = true;
				}
			}
		}

//		Product producto1 = new Product(10, "Android HTC", 2, 5,
//				"De los mejorcitos", "PathFoto");
//		Product producto2 = new Product(11, "Android nt720", 13, 5,
//				"Tira... hasta ahi", "PathFoto");
//		Product producto3 = new Product(12, "Windows", 4, 1, "Se tilda...",
//				"PathFoto");
//
//		Customer cliente1 = new Customer(1, "Exequiel", "156765477",
//				"exe@exe.com", "Primero de Mayo 1515", "Rosario");
//		Customer cliente2 = new Customer(2, "Peter", "153373674",
//				"peter64peter.com", "Primero de Mayo 520", "Rosario");
//		Customer cliente3 = new Customer(3, "Otro", "23452345", "xxx@xxx.com",
//				"XXXXXXXXXXX", "Santa Fe");
//
//		ArrayList<Product> prod = new ArrayList<Product>();
//		prod.add(producto1);
//		prod.add(producto2);
//		prod.add(producto3);
//		cliente1.setProducts(prod);
//		prod.remove(producto1);
//		cliente2.setProducts(prod);
//
//		Iterator<Product> iterator = prod.iterator();
//		while (iterator.hasNext()) {
//			System.out.println(iterator.next());
//		}
//
//		manager = DatabaseManager.getInstance();
//
//		manager.addCustomer(cliente1);
//		manager.addCustomer(cliente2);
		
		
		// List<Categorie> list_categoria = manager.getAllCategories();

		txt_name = (EditText) findViewById(R.id.addproduct_edittext_name);
		txt_quantity = (EditText) findViewById(R.id.addproduct_edittext_quantity);
		sp_categorie = (Spinner) findViewById(R.id.addproduct_spinner_categorie);
		txt_description = (EditText) findViewById(R.id.addproduct_edittext_description);
		imageView = (ImageView) findViewById(R.id.addproduct_image_showPhoto);
		btn_photo = (Button) findViewById(R.id.addproduct_button_addPhoto);

		btn_photo.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {

				Intent intent = new Intent(
						android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
				startActivityForResult(intent, CAMERA_PIC_REQUEST);
			}
		});

		imb_delete = (ImageButton) findViewById(R.id.addproduct_imagebutton_delete);

		imb_delete.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				int id = ProductActivity.productEdit.getProductId();
				// TITTLE & TEXT
				String title = getResources().getString(R.string.products);
				String text = getResources().getString(
						R.string.do_you_want_to_delete_this_item_);

				customDialog = showDialogEliminar(text, title, id);
				customDialog.show();
			}
		});

		utilman = Util.getInstanceUtil();
		manager = DatabaseManager.getInstance();

		mContext = getApplicationContext();

		btn_cancel = (Button) findViewById(R.id.addproduct_button_cancel);
		btn_cancel.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});

		btn_save = (Button) findViewById(R.id.addproduct_button_save);
		btn_save.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				validate();
			}
		});

		sp_categorie.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parentView,
					View selectedItemView, int position, long id) {
				// TODO Auto-generated method stub

				String Text = sp_categorie.getSelectedItem().toString();

				loadCategories(Text);

			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub

			}

		});

		if (isEditMode) {
			btn_save.setText(getString(R.string.update));

			product = manager.getProductByID(ProductActivity.productEdit.getProductId());

			txt_name.setText("" + product.getName());
			txt_quantity.setText("" + product.getQuantity());
			txt_quantity.setEnabled(false);
			pathphoto = product.getPhoto();
			idcategorie = product.getCategorie();
			loadCategories(idcategorie);

			txt_description.setText("" + product.getDesc());
			
			
			
			try {
				if(!pathphoto.equals("")){
					String strFile = Environment.getExternalStorageDirectory()+ "/" + PATH_APPDIRs  + "/" + pathphoto ;
					File file = new File( strFile );		
					System.out.println ("productactivity  foto : " + strFile);
					if(file.exists())
					{ 
						Bitmap myBitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
						imageView.setImageBitmap(myBitmap);
					}
					
				}
				
			} catch (Exception e) {
				e.printStackTrace();
			}

		} else {
			loadCategories(idcategorie);
		}

	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == CAMERA_PIC_REQUEST
				&& resultCode == Activity.RESULT_OK) {

			if (bitmap != null) {
				bitmap.recycle();
			}

			if (Util.checkExternalMedia() == false) {
				
				Toast.makeText(this, "Can't create directory to save image. ", Toast.LENGTH_LONG).show();
				
				return ;
			}
			
			File pictureFileDir = getDir();

			if (!pictureFileDir.exists() && !pictureFileDir.mkdirs()) {

				Toast.makeText(this, "Can't create directory to save image.",
						Toast.LENGTH_LONG).show();
				// return;

			}

			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			bitmap = (Bitmap) data.getExtras().get("data");
			bitmap.compress(CompressFormat.JPEG, 95, bos);


			imageView.setImageBitmap(bitmap);

			try {

				byte[] foto = bos.toByteArray();

				Date fecha = new Date();
				SimpleDateFormat ft = new SimpleDateFormat("yyyy_MM_dd_hhmmss");
				String fechaCompleta = ft.format(fecha);

				

				File imagesFolder = null;
				try {
					imagesFolder = new File(Environment.getExternalStorageDirectory(), PATH_APPDIRs);
				
					Log.d("MAKE DIR", imagesFolder.mkdirs() + "");
					imagesFolder.mkdirs();
				} catch (Exception e) {
					Log.d("MAKE DIR", e.getMessage().toString());
					return ;
				}
				picturFile = fechaCompleta + ".jpg";
				
				pathphoto = picturFile;
				
				
				String strFile = Environment.getExternalStorageDirectory() + "/" + PATH_APPDIRs +"/"+ picturFile;
				System.out.println ("addproduct foto : " + strFile);
				File picture = new File(strFile);
		
				
				if (picture.exists() == true) {
					System.out.println("Se ha creado el siguiente Path: "+ picture.getAbsolutePath());
				} else {
					//System.out.println("No se ha creado nada...");
					picture.createNewFile();
				}

				FileOutputStream out = new FileOutputStream(picture);

				// product =
				// manager.getProductByID(ProductActivity.productEdit.getProductId());
				// filename = product.getProductId() + ".png";

				out.write(foto);
				out.close();

				thumbnail = BitmapFactory.decodeByteArray(foto, 0, foto.length);
				final Bitmap imagenfinal = BitmapFactory.decodeByteArray(foto,0, foto.length);

			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}

	}

	private File getDir() {
		File sdDir = Environment
				.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
		return new File(sdDir, "CameraAPIDemo");
	}

	// @Override
	// public boolean onCreateOptionsMenu(Menu menu) {
	// getMenuInflater().inflate(R.menu.activity_add_product, menu);
	// return true;
	// }

	private void loadCategories(int idITEM) {
		List<Categorie> list_categoria = manager.getAllCategories();
		String[] str_categories = new String[list_categoria.size()];

		int itemSelection = 0;

		int i = 0;
		int selItem = 0;
		for (Categorie item : list_categoria) {
			str_categories[i] = item.getName();

			if (idITEM != -1) {
				// if( str_categories[i].equals( String.valueOf(idITEM)) ){
				if (idITEM == item.getId()) {
					itemSelection = i;
					// sp_categorie.setSelection(i);
					// break;
				}
			}

			i++;
		}

		ArrayAdapter<String> adapter = new ArrayAdapter<String>(
				AddProductActivity.this, android.R.layout.simple_spinner_item,
				str_categories);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		sp_categorie.setAdapter(adapter);

		sp_categorie.setSelection(itemSelection);
		// return selItem;

	}

	private void loadCategories(String str) {
		List<Categorie> list_categoria = manager.getAllCategories();
		String[] str_categories = new String[list_categoria.size()];
		int i = 0;
		int selItem = 0;
		for (Categorie item : list_categoria) {
			str_categories[i] = item.getName();

			if (str_categories[i].equals(str)) {
				idcategorie = item.getId();

			}

			i++;
		}

	}

	private void validate() {
		
		if (txt_name.getText().toString().equals("")
				|| txt_name.getText().toString().equals("")
				|| txt_quantity.getText().toString().equals("")
				|| txt_quantity.getText().toString().equals("")) {
			dialog_confirmation = utilman
					.showDialog(
							getString(R.string.complete_all_required_fields_before_continue),
							getString(R.string.atention),
							AddProductActivity.this);
			try {
				dialog_confirmation.show();
			} catch (Exception e) {
				e.printStackTrace();
			}

		} else {

			int quantity = Integer.parseInt(txt_quantity.getText().toString());

			String description = txt_description.getText().toString();
			
			System.out.println ("product foto : " + pathphoto);

			if (product != null) {
		
				product.setName(txt_name.getText().toString());
				product.setCategorie(idcategorie);
				product.setDescription(description);
				product.setPhoto(pathphoto);
				product.setQuantity(quantity);
				//product.setProductId(manager.getIdByName(txt_name.getText().toString()));
				
				//Peter	
//				if (stock != null) {
//						
//				Date fecha = new Date();
//				SimpleDateFormat ft = new SimpleDateFormat("yyyy_MM_dd_hhmm");
//				String fechaCompleta = ft.format(fecha);
//	
//				stock.setProduct_id(product.getProductId());
//				stock.setQuantity(product.getQuantity());
//				stock.setMovement_date(fechaCompleta);
//			
//				}
				//fin peter	
				
			} else {
			
				pathphoto = "";
				product = new Product(txt_name.getText().toString(),
						quantity, idcategorie, description, pathphoto, ACTIVO);
				
				manager.addProduct(product);
				//peter
				stock =new Stock(new Date().toString() ,product.getProductId(), quantity);
				
				//fin peter
			}

			if (isEditMode) {

				//peter
				stock =new Stock(new Date().toString() ,product.getProductId(), quantity);
				manager.addStock(stock);
				
				int stock_quantity  = manager.getQuantityByProductId(stock.getProduct_id());
				stock.setQuantity(stock_quantity);
				boolean ret = manager.updateProduct(product);
				
				
				
				
				if (ret) {
					Toast.makeText(mContext,
							getString(R.string.the_item_is_updated),
							Toast.LENGTH_LONG).show();
				} else {
					Toast.makeText(mContext,
							getString(R.string.failed_to_update_the_item),
							Toast.LENGTH_LONG).show();

				}
				
				

				
			//	stock.setProduct_id(product.getProductId());
			//	stock.setQuantity(product.getQuantity());
			//	stock.setMovement_date(new Date().toString());
				
			//	manager.addStock(stock);

				
				//fin peter
			
				
			//if we are adding a new product
			} else {
				
				
				//Peter	
				Date fecha = new Date();
				SimpleDateFormat ft = new SimpleDateFormat("yyyy_MM_dd_hhmmss");
				String fechaCompleta = ft.format(fecha);

				
				stock.setProduct_id(product.getProductId());
				stock.setQuantity(manager.getIdProductFromDB(txt_name.getText().toString()));
				stock.setMovement_date(fechaCompleta);
				//fin Peter	
				
				
				
				manager.addStock(stock);

				Toast.makeText(mContext, "The new item is added",Toast.LENGTH_LONG).show();
			}

			finish();
		}

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		// return super.onCreateOptionsMenu(menu);

		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.add_product, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem menu) {
		// TODO Auto-generated method stub
		// return super.onOptionsItemSelected(menu);

		if (menu.getItemId() == R.id.menu_addproduct_categorie) {
			Intent intent = new Intent();
			intent.setClass(mContext, CategoriesActivity.class);
			startActivity(intent);

			return true;
		}

		return false;
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		loadCategories(idcategorie);
	}

	/**
	 * @param String
	 *            message
	 * @param String
	 *            title
	 * @return
	 */
	public Dialog showDialogEliminar(String message, String title, final int ID) {
		//

		customDialog = new Dialog(AddProductActivity.this);
		customDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		customDialog.setContentView(R.layout.simpledialog_okcancel);
		customDialog.setCancelable(false);

		TextView tv_title = (TextView) customDialog
				.findViewById(R.id.simpledialog_okcancel_title);
		TextView tv_text = (TextView) customDialog
				.findViewById(R.id.simpledialog_okcancel_text);
		Button btn_ok = (Button) customDialog
				.findViewById(R.id.simpledialog_okcancel_ok);
		Button btn_cancel = (Button) customDialog
				.findViewById(R.id.simpledialog_okcancel_cancel);

		tv_title.setText(title);
		tv_text.setText(message);

		btn_ok.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				manager.deleteProductByID(ID);
				customDialog.cancel();
				finish();
			}
		});

		btn_cancel.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				customDialog.cancel();
				// finish();
			}
		});

		return customDialog;
	}
}
